//
// async_udp_echo_server.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2021 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// ref: https://www.boost.org/doc/libs/1_78_0/doc/html/boost_asio/example/cpp11/echo/async_udp_echo_server.cpp
//

#include <boost/asio.hpp>
#include <boost/version.hpp>
#include <cstdlib>
#include <iostream>

using namespace boost;
using boost::asio::ip::udp;

class server {

    enum { max_length = 1024 };
    char data_[max_length];
    udp::endpoint sender_endpoint_;
    boost::asio::io_context io_context;
    udp::socket socket_;

public:
    server(int port)
        : socket_(io_context, udp::endpoint(udp::v4(), port))
    {
    }

    void do_recevie()
    {
        socket_.async_receive_from(
            boost::asio::buffer(data_, max_length), sender_endpoint_,
            [this](boost::system::error_code ec, std::size_t bytes_recvd) {
                std::cout << "recive from: "
                          << sender_endpoint_.address() << ":"
                          << sender_endpoint_.port() << " "
                          /* << sender_endpoint_.protocol()  */
                          << "\n";

                if (!ec && bytes_recvd > 0) {
                    do_send(bytes_recvd);
                } else {
                    do_recevie();
                }
            });
    }

    void do_send(std::size_t length)
    {
        socket_.async_send_to(
            boost::asio::buffer(data_, length), sender_endpoint_,
            [this](boost::system::error_code /*ec*/, std::size_t /*bytes_sent*/) {
                do_recevie();
            });
    }

    void start()
    {
        do_recevie();
        io_context.run();
    }
};

class client {
    // 这个才是更像pc端

public:
    void start(int port)
    {
        boost::asio::io_context io_context;
        udp::endpoint send_ep(boost::asio::ip::address::from_string("127.0.0.1"), port); // to fpga
        // udp::endpoint recv_ep(udp::v4(), 0); // from local pc, 发送端口，port为0时，系统随机分配
        udp::endpoint recv_ep(udp::v4(), port + 1); // from local pc
        udp::socket socket(io_context, recv_ep); // recive

        std::cout << "recive socket info: "
                  << recv_ep.address() << ":"
                  << recv_ep.port() << " "
                  /* << send_ep2.protocol() */
                  << "\n";

        char buf[1024];
        socket.send_to(boost::asio::buffer("message"), send_ep);
        udp::endpoint send_ep2; // recv peer ep, 这是收到包之后的第二次发的ep, 这里后面实际不用
        int bytes = socket.receive_from(boost::asio::buffer(buf), send_ep2);

        std::string recv_msg(buf, bytes);
        std::cout << "recive from: "
                  << send_ep2.address() << ":"
                  << send_ep2.port() << " "
                  /* << send_ep2.protocol() */
                  << "\n";
        std::cout << "server echoed us: msg: >>> " << recv_msg << "\n";

        socket.send_to(boost::asio::buffer("message"), send_ep2);
        socket.close();
    }
};

int main(int argc, char* argv[])
{
    std::cout << "use boost version: " << BOOST_LIB_VERSION << std::endl;
    try {
        if (argc != 4) {
            std::cerr << "Usage: test [s|c] ip port\n";
            return 1;
        }

        if (argv[1][0] == 'c') {
            // client
            client().start(std::atoi(argv[3]));

        } else if (argv[1][0] == 's') {
            // server
            server(std::atoi(argv[3])).start();
        }
    } catch (std::exception& e) {
        std::cerr << "Exception: " << e.what() << "\n";
    }
    return 0;
}